<template>
  <Header></Header>
  <div class="content">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="账号安全" name="first">
        <el-form label-position="top">
          <el-form-item label="邮箱">
            <el-input
              disabled
              style="flex: 6; margin-right: 30px"
              :placeholder="`可以使用邮箱${userInfo.email}直接登录，重置密码或其他安全验证`"
            ></el-input>
            <el-button
              @click="
                centerDialogVisible = true;
                editId = 2;
              "
              style="flex: 1"
              >修改</el-button
            >
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              disabled
              style="flex: 6; margin-right: 30px"
              :placeholder="`可以使用手机${userInfo.phone}直接登录，重置密码或其他安全验证`"
            ></el-input>
            <el-button
              @click="
                centerDialogVisible = true;
                editId = 1;
              "
              style="flex: 1"
              >修改</el-button
            >
          </el-form-item>
          <el-form-item label="密码">
            <el-input
              disabled
              style="flex: 6; margin-right: 30px"
              placeholder="*******"
            ></el-input>
            <el-button
              @click="
                centerDialogVisible = true;
                editId = 3;
              "
              style="flex: 1"
              >修改</el-button
            >
          </el-form-item>
        </el-form>
        <el-dialog
          v-model="centerDialogVisible"
          title="身份验证"
          width="500"
          align-center
        >
          <el-form label-position="top">
            <el-form-item label="验证方式">
              <el-select v-model="identityType">
                <el-option
                  :label="`使用手机 ${userInfo.phone} 验证`"
                  :value="1"
                />
                <el-option
                  :label="`使用邮箱 ${userInfo.email} 验证`"
                  :value="2"
                />
                <!-- <el-option label="使用赛氪登录密码验证" :value="3" /> -->
              </el-select>
            </el-form-item>
            <el-form-item label="验证码" v-if="identityType != 3">
              <el-input
                v-model="code"
                style="width: 200px; margin-right: 20px"
              ></el-input>
              <el-button
                @click="
                  getCode(
                    identityType,
                    identityType == 2 ? userInfo.email : userInfo.phone
                  )
                "
              >
                获取验证码
              </el-button>
            </el-form-item>
            <el-form-item label="密码" v-else>
              <el-input
                v-model="code"
                placeholder="请输入登录密码"
                style="width: 200px; margin-right: 20px"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="centerDialogVisible = false">取消</el-button>
              <el-button @click="cehckUserInfo" type="primary">
                验证
              </el-button>
            </div>
          </template>
        </el-dialog>

        <el-dialog
          v-model="centerEditDialogVisible"
          title="修改"
          width="500"
          align-center
        >
          <el-form label-position="top">
            <template v-if="editId == 2">
              <el-form-item label="请输入新邮箱">
                <el-input
                  style="margin-right: 20px"
                  placeholder="请输入新邮箱"
                  v-model="newUserInfo.email"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="newUserInfo.code"
                  style="width: 200px; margin-right: 20px"
                ></el-input>
                <el-button @click="getCode(2, newUserInfo.email)">
                  获取验证码
                </el-button>
              </el-form-item>
            </template>
            <template v-else-if="editId == 1">
              <el-form-item label="请输入新手机号">
                <el-input
                  style="margin-right: 20px"
                  placeholder="请输入新手机号"
                  v-model="newUserInfo.phone"
                />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="newUserInfo.code"
                  style="width: 200px; margin-right: 20px"
                ></el-input>
                <el-button @click="getCode(1, newUserInfo.phone)">
                  获取验证码
                </el-button>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="密码">
                <el-input
                  v-model="newUserInfo.code"
                  placeholder="请输入登录密码"
                  style="width: 200px; margin-right: 20px"
                ></el-input>
              </el-form-item>
            </template>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="centerDialogVisible = false">取消</el-button>
              <el-button @click="modifyUserInfo" type="primary">
                修改
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="个人信息" name="个人信息">
        <el-button
          type="success"
          plain
          size="mini"
          @click="centerEditUserInfoDialogVisible = true"
          >修改</el-button
        >
        <el-descriptions title="基本资料">
          <el-descriptions-item>
            <el-avatar
              shape="square"
              :size="100"
              fit="fill"
              :src="`${userInfo.avatar}`"
          /></el-descriptions-item>
          <el-descriptions-item label="姓名">{{
            userInfo.name
          }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{
            userInfo.nickName
          }}</el-descriptions-item>
          <el-descriptions-item label="签名">{{
            userInfo.signature
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-tag size="small" v-if="userInfo.sex == 0">男</el-tag>
            <el-tag size="small" v-else>女</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否为组织">
            <el-tag size="small" v-if="userInfo.isOrganization == 0"
              >组织者账号</el-tag
            >

            <el-button v-else @click="applyButton" style="flex: 1"
              >申请</el-button
            ></el-descriptions-item
          >
        </el-descriptions>

        <el-dialog
          v-model="dialogFormVisibleCAS"
          title="申请成为组织者账号"
          width="800"
        >
          <el-form
            label-position="top"
            :model="organizationForm"
            :disabled="organizationForm.status != 0"
          >
            <el-form-item label="申请理由">
              <AiEditor
                v-model="organizationForm.casContentCAS"
                :disabled="organizationForm.status != 0"
              />
            </el-form-item>
            <el-form-item label="证明材料">
              <el-upload
                action="http://117.72.35.196:8848/common/upload"
                :on-success="handleSuccess"
                list-type="picture-card"
                :multiple="false"
                :auto-upload="true"
                :disabled="organizationForm.status != 0"
                v-model:file-list="fileListCAS"
              >
                <el-icon><Plus /></el-icon>

                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreviewCAS(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        v-if="!disabledCAS"
                        class="el-upload-list__item-delete"
                        @click="handleRemoveCAS(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisibleCAS = false">取消</el-button>
              <el-button
                type="primary"
                :disabled="organizationForm.status != 0"
                @click="commitCAS(0)"
              >
                保存
              </el-button>
              <el-button
                type="warning"
                :disabled="organizationForm.status != 0"
                @click="commitCAS(1)"
              >
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
        <el-dialog
          v-model="centerEditUserInfoDialogVisible"
          title="修改个人信息"
          width="500"
          align-center
        >
          <el-form :model="userInfo">
            <el-form-item label="头像">
              <el-upload
                action="http://117.72.35.196:8848/common/upload"
                list-type="picture-card"
                :limit="1"
                :file-list="[{ url: `${userInfo.avatar}` }]"
                :on-success="handlePictureCardSuccess"
                :on-preview="handlePictureCardPreview"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible="dialogVisible">
                <img width="100%" :src="userInfo.avatar" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item label="	姓名">
              <el-input v-model="userInfo.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="	昵称">
              <el-input v-model="userInfo.nickName" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="	签名">
              <el-input v-model="userInfo.signature" placeholder="请输入签名" />
            </el-form-item>
            <el-form-item label="	性别">
              <el-select v-model="userInfo.sex" placeholder="请选择性别">
                <el-option label="男" :value="0" />
                <el-option label="女" :value="1" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="centerEditUserInfoDialogVisible = false"
                >取消</el-button
              >
              <el-button @click="changeUserinfo" type="primary">
                修改
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>

  <FixedMenu />
  <Footer></Footer>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  ElMessage,
  type TabsPaneContext,
  type UploadProps,
  type ElForm,
  type UploadFile,
} from "element-plus";

import {
  editUserimpifmInfo,
  sendEmailValidateCode,
  sendValidateCode,
  editUserInfo,
  checkIdentity,
  getLoginUserInfo,
  userCheckInsert,
  userCheckUpdate,
  userCheckGet,
} from "@/api/user";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
const activeName = ref("first");
const dialogFormVisibleCAS = ref(false);
// let casContentCAS = ref(""); // 富文本
let imageCAS = ref<string[]>([]); // 图片 list
const disabledCAS = ref(false);
const handleSuccess: UploadProps["onSuccess"] = ({}, response: any) => {
  organizationForm.imageCAS.push(
    `http://117.72.35.196:8848/common/download?fileName=${response.response.fileName}`
  );
};

let fileListCAS = ref<UploadFile[]>([]); // 文件list对象
const organizationForm = reactive({
  status: 0,
  casContentCAS: "",
  imageCAS: [],
});
// 图片预览
const handlePictureCardPreviewCAS = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};
// 图片删除
const handleRemoveCAS = (file: UploadFile) => {
  if (organizationForm.status != 0) return;
  const index = fileListCAS.value.indexOf(file);
  fileListCAS.value.splice(index, 1);
};
const applyButton = () => {
  userCheckGet().then(({ data }) => {
    if (data.data != undefined) {
      organizationForm.casContentCAS = data.data.content;
      organizationForm.imageCAS =
        data.data.material == ""
          ? data.data.material.split("")
          : data.data.material.split(",");
      organizationForm.status = data.data.status;
      organizationForm.id = data.data.id;
      fileListCAS.value = [];
    }
    organizationForm.imageCAS.forEach((item) => {
      const obj = {
        url: item,
      };
      fileListCAS.value.push(obj);
    });
    dialogFormVisibleCAS.value = true;
  });
};
// 申请成为组织者账号的回调
const commitCAS = (status) => {
  // 校验参数
  if (organizationForm.casContentCAS.trim() === "") {
    ElMessage.error("申请理由不能为空");
    return;
  }
  if (organizationForm.imageCAS.length === 0) {
    ElMessage.error("请上传证明材料");
    return;
  }
  const id = organizationForm.id || undefined;
  const params = {
    content: organizationForm.casContentCAS,
    material: organizationForm.imageCAS.join(),
    status: status,
  };
  let msg = "保存成功";
  if (status == 1) {
    msg = "提交成功";
  }
  if (id == undefined) {
    userCheckInsert(params).then((res) => {
      // 发送请求
      disabledCAS.value = true;
      ElMessage.success(msg);
      // 关闭弹窗
      dialogFormVisibleCAS.value = false;
      disabledCAS.value = false;
    });
  } else {
    params.id = id;
    userCheckUpdate(params).then((res) => {
      // 发送请求
      disabledCAS.value = true;
      ElMessage.success(msg + "，请等待审核");
      // 关闭弹窗
      dialogFormVisibleCAS.value = false;
      disabledCAS.value = false;
    });
  }
};
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handlePictureCardPreview = (file: UploadFile) => {
  userInfo.avatar = file?.url as string;
  dialogVisible.value = true;
};
// 图片上传
const handlePictureCardSuccess = ({}, file: any) => {
  console.log(file);
  userInfo.avatar = file.response.url;
};

let userInfo = reactive({
  avatar: "",
  degree: "",
  signature: "",
  name: "",
  email: "",
  isOrganization: "",
  nickName: "",
  phone: "",
  sex: "",
  userInformationList: [],
});
onMounted(() => {
  getLoginUserInfo().then(({ data }) => {
    Object.assign(userInfo, data.data);
  });
});
// 修改信息验证身份的dialog
const centerDialogVisible = ref(false);
const centerEditDialogVisible = ref(false);
const centerEditUserInfoDialogVisible = ref(false);

let newUserInfo = ref({
  code: "",
  email: "",
  phone: "",
});
const changeUserinfo = async () => {
  const data = await editUserInfo(userInfo);
  if (data.data.code === 200) {
    centerEditUserInfoDialogVisible.value = false;
    ElMessage.success("修改成功");
  } else {
    ElMessage.error("修改失败");
  }
};
const code = ref("");
let identityType = ref(1);
let editId = ref(2);
// 获取验证码
const getCode = async (type: number, info: string) => {
  if (type == 1) {
    const result = await sendValidateCode(info);
    if (result.code === 200) {
      // TODO: 显示验证码
    }
  } else {
    const result = await sendEmailValidateCode(info);
    if (result.code === 200) {
      // TODO: 显示验证码
    }
  }
};
//验证信息
const cehckUserInfo = async () => {
  const { data } = await checkIdentity(identityType.value, code.value);
  if (data.code == 200) {
    centerDialogVisible.value = false;
    centerEditDialogVisible.value = true;
  } else {
    ElMessage.error("验证失败");
  }
};
// 修改信息
const modifyUserInfo = async () => {
  const pData = {
    type: editId.value,
    checkCode: newUserInfo.value.code,
    changeString: newUserInfo.value.code,
  };
  // // TODO: 验证通过
  const data = await editUserimpifmInfo(pData);
  if (data.data.code === 200) {
    centerEditDialogVisible.value = false;
    ElMessage.success("修改成功");
  } else {
    ElMessage.error("修改失败");
  }
};
</script>

<style lang="scss" scoped>
.content {
  box-sizing: border-box;
  margin: 20px auto;
  max-width: 800px;
  padding: 20px;
}
:deep(.el-input__wrapper) {
  padding: 0;
}
.common-form-line {
  margin-top: 30px;
}
.common-form-label {
  font-size: 16px;
  min-height: 26px;
}
.field {
  margin-right: 20px;
}
.clearfix {
  overflow: hidden;
  zoom: 1;
}
.common-input {
  width: 664px;
}
.common-input {
  float: left;
  width: 70%;
}
.common-input input[readonly] {
  border: 1px solid #dedede;
  background: #f4f4f4;
}
.common-input input {
  outline: none;
  height: 46px;
  background: #fff;
  border-radius: 3px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  width: 100%;
  line-height: inherit;
  padding: 0 15px;
}
.sk-btn {
  color: #22bfa7;
  margin-right: 0;
  width: 15%;
  border-radius: 3px;
  cursor: pointer;
  float: right;
  height: 44px;
  line-height: 44px;
  display: inline-block;
  font-size: 16px;
  padding: 0 22px;
  text-align: center;
  border: 1px solid #22bfa7;
  -webkit-transition: all 0.2s ease;
  -moz-transition: all 0.2s ease;
  -ms-transition: all 0.2s ease;
  transition: all 0.2s ease;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}
// :deep(.el-input__wrapper) {
//     padding: 0;
// }
</style>
